package com.qiwx.pigeon.Utils;

import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.qiwx.pigeon.R;
import com.qiwx.pigeon.app.AppContext;

import java.util.Timer;
import java.util.TimerTask;

public class MyToast {
	private static Toast toast;
	public static void showLong(String content){
		show(content, Toast.LENGTH_LONG);
	}
	public static void showShort(int resId){
		show(resId, Toast.LENGTH_SHORT);
	}
	public static void showLong(int resId){
		show(resId, Toast.LENGTH_LONG);
	}


	public static void showShort(String content){
		show(content, Toast.LENGTH_SHORT);
	}
	private static void show(Object obj, int duration){
		try{
//			Looper.prepare();
			if (toast == null) {
				initToast();
			}
			toast.setDuration(Toast.LENGTH_SHORT);
			if(obj instanceof Integer){
				setText((int)obj);
			}else if(obj instanceof String){
				setText((String)obj);
			}

			toast.show();
//			Looper.loop();
		}catch (Exception e){
			e.printStackTrace();
		}


	}
	//
	public static void showCenterShort(String content){
		if (toast == null) {
			initToast();
		}
		try {
			toast.setDuration(Toast.LENGTH_SHORT);
			toast.setGravity(Gravity.CENTER,0,0);
			setText(content);
			toast.show();
		}catch (Exception e){
			e.printStackTrace();
		}

	}

	private static void initToast() {
		toast = new Toast(AppContext.getContext());
		View inflate = LayoutInflater.from(AppContext.getContext()).inflate(R.layout.custom_toast_layout, null);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setView(inflate);
	}

	private static void setText(String content) {
		TextView textView = (TextView) toast.getView().findViewById(R.id.message);
		textView.setText(content);
	}

	private static void setText(int resourceId) {
		TextView textView = (TextView) toast.getView().findViewById(R.id.message);
		textView.setText(resourceId);
	}

	public static void showMyToast(final Toast toast, final int cnt) {
		final Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				toast.show();
			}
		}, 0, 3000);
		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				toast.cancel();
				timer.cancel();
			}
		}, cnt );
	}

}
